package com.example.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.app.RoomApp
import com.example.ksproomdemo.bean.User
import com.example.ksproomdemo.dao.UserDao

/**
 * @author: njb
 * @date:   2025/3/30 1:25
 * @desc:   数据库基础类
 */
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}
class RoomUtils private constructor(){
    private val database: AppDatabase by lazy {
        Room.databaseBuilder(
            RoomApp.instance.applicationContext,
            AppDatabase::class.java, "app-database"
        ).build()
    }

    companion object {
        @Volatile
        private var instance: RoomUtils? = null

        fun getInstance(): RoomUtils {
            return instance ?: synchronized(this) {
                instance ?: RoomUtils().also { instance = it }
            }
        }
    }

    private val userRepository: UserRepository by lazy {
        UserRepository(database.userDao())
    }

    suspend fun insertUser(user: User) {
        userRepository.insertUser(user)
    }

    suspend fun updateUser(user: User) {
        userRepository.updateUser(user)
    }

    suspend fun deleteUser(user: User) {
        userRepository.deleteUser(user)
    }

    suspend fun getAllUsers(): List<User> {
        return userRepository.getAllUsers()
    }

    suspend fun deleteUsers(user: List<User>) {
        return userRepository.deleteUsers(user)
    }


    suspend fun deleteAllUser() {
        userRepository.deleteAllUser()
    }
}